/**
 * 
 */
package com.jeesuite.bestpl.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageInfo;
import com.jeesuite.bestpl.api.IUserScoreService;
import com.jeesuite.bestpl.dao.entity.UserScoreEntity;
import com.jeesuite.bestpl.dao.entity.UserScoreLogEntity;
import com.jeesuite.bestpl.dao.mapper.UserScoreEntityMapper;
import com.jeesuite.bestpl.dao.mapper.UserScoreLogEntityMapper;
import com.jeesuite.bestpl.dto.UserScore;
import com.jeesuite.bestpl.dto.UserScoreLog;
import com.jeesuite.common.util.BeanCopyUtils;
import com.jeesuite.common2.lock.MultiRetryLock;
import com.jeesuite.mybatis.page.PageDataLoader;
import com.jeesuite.mybatis.page.PageTemplate;

/**
 * @description <br>
 * @author <a href="mailto:vakinge@gmail.com">vakin</a>
 * @date 2016年10月25日
 */
@Service("userScoreService")
public class UserScoreServiceImpl implements IUserScoreService {

	private @Autowired UserScoreEntityMapper userScoreMapper;
	private @Autowired UserScoreLogEntityMapper userScoreLogMapper;
	@Override
	@Transactional
	public void addScore(int userId,int score,String remark) {
		//这里加分布式锁，避免多端同时操作
		MultiRetryLock lock = new MultiRetryLock("addscore.lock:"+userId);
		try {
			lock.lock();			
			UserScoreEntity scoreEntity = userScoreMapper.findByUsertId(userId);
			if(scoreEntity == null){
				scoreEntity = new UserScoreEntity();
				scoreEntity.setUserId(userId);
				scoreEntity.setLastScore(0);
				scoreEntity.setUpdatedAt(new Date());
				scoreEntity.setCurrentScore(score);
				userScoreMapper.insertSelective(scoreEntity);
			}else{			
				scoreEntity.setLastScore(scoreEntity.getCurrentScore());
				scoreEntity.setCurrentScore(scoreEntity.getCurrentScore() + score);
				scoreEntity.setUpdatedAt(new Date());
				userScoreMapper.updateByPrimaryKeySelective(scoreEntity);
			}
			//add userScoreLog
			
		} finally {
			lock.unlock();
		}
	}

	@Override
	public PageInfo<UserScoreLog> pageQuery(int pageNo, int pageSize, final int userId) {
		
		PageInfo<UserScoreLog> result = null;
		PageInfo<UserScoreLogEntity> pageInfo = PageTemplate.execute(pageNo, pageSize, new PageDataLoader<UserScoreLogEntity>() {
			@Override
			public List<UserScoreLogEntity> load() {
				return userScoreLogMapper.findByUsertId(userId);
			}
		});
		//bean转换
		List<UserScoreLog> datas = BeanCopyUtils.copy(pageInfo.getList(), UserScoreLog.class);
		pageInfo.setList(null);
		result = BeanCopyUtils.copy(pageInfo, PageInfo.class);
		result.setList(datas);
		
		return result;
	}

	@Override
	public UserScore findUserScoreByUserId(int userid) {
		UserScoreEntity entity = userScoreMapper.findByUsertId(userid);
		return BeanCopyUtils.copy(entity, UserScore.class);
	}
	
}
